package com.huawei.esdk.uc.sametime.widgets;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;

import com.huawei.esdk.uc.sametime.international.Messages;
import com.huawei.esdk.uc.sametime.util.PersonInviteUtil;
import com.huawei.esdk.uc.sametime.util.PluginUtil;
import com.ibm.collaboration.realtime.contacts.search.DirectoryInfo;
import com.ibm.collaboration.realtime.people.Person;

public class PersonSelectDialog extends Dialog implements
        PersonSelectHandlerInterface
{
    private static Logger logger = Logger.getLogger(PersonSelectDialog.class);

    private TableViewer toInviteTableViewer;

    private Table toInviteTable;

    private CustomQuickFindWidget quickSearchComposite;

    private Button delButton;

    private Map<String, Person> toInviteContactMap;

    private Person[] toInviteContactArray;

    /**
     * Create the dialog.
     * @param parentShell
     */
    public PersonSelectDialog(Shell parentShell)
    {
        super(parentShell);
        toInviteContactMap = new HashMap<String, Person>();
        PersonInviteUtil.getInstance().setSelectedPerson(null);

    }

    @Override
    protected void configureShell(Shell shell)
    {
        super.configureShell(shell);
        shell.setText(Messages.PersonSelectDialog_INVITE_TITLE);
    }

    /**
     * Create contents of the dialog.
     * @param parent
     */
    @Override
    protected Control createDialogArea(Composite parent)
    {
        Composite container = (Composite) super.createDialogArea(parent);
        container.setLayout(null);

        quickSearchComposite = new CustomQuickFindWidget(container, SWT.NONE);
        quickSearchComposite.setBounds(25, 10, 500, 30);
        quickSearchComposite.setHandler(this);

        delButton = new Button(container, SWT.NONE);
        delButton.setBounds(436, 46, 89, 27);
        delButton.setText(Messages.DELETE);
        delButton
                .setToolTipText(Messages.PersonSelectDialog_DEL_FROM_INVITE_TABLE);

        toInviteTableViewer = new TableViewer(container, SWT.BORDER
                | SWT.FULL_SELECTION);
        InviteTableLabelProvider inviteTableLabelProvider = new InviteTableLabelProvider();
        toInviteTableViewer.setLabelProvider(inviteTableLabelProvider);
        InviteTableContentProvider inviteTableContentProvider = new InviteTableContentProvider();
        toInviteTableViewer.setContentProvider(inviteTableContentProvider);
        toInviteTable = toInviteTableViewer.getTable();
        toInviteTable.setLinesVisible(true);
        toInviteTable.setHeaderVisible(true);
        toInviteTable.setBounds(25, 82, 500, 137);
        createToInviteTableHeader();
        addInviteTableListener();
        addDelButtonListener();

        return container;
    }

    private void createToInviteTableHeader()
    {
        TableColumn tc;
        String[] contactColumnHeaders = new String[4];
        contactColumnHeaders[0] = Messages.PersonSelectDialog_NICK_NAME;
        contactColumnHeaders[1] = Messages.PersonSelectDialog_UID;
        contactColumnHeaders[2] = Messages.PersonSelectDialog_TELEPHONE;
        contactColumnHeaders[3] = Messages.PersonSelectDialog_MAIL;

        // nickname column
        tc = new TableColumn(toInviteTable, SWT.NONE);
        tc.setText(contactColumnHeaders[0]);
        tc.setAlignment(SWT.CENTER);
        tc.setWidth(200);

        // uid column
        tc = new TableColumn(toInviteTable, SWT.NONE);
        tc.setText(contactColumnHeaders[1]);
        tc.setAlignment(SWT.CENTER);
        tc.setWidth(200);

        // mail column
        tc = new TableColumn(toInviteTable, SWT.NONE);
        tc.setText(contactColumnHeaders[2]);
        tc.setAlignment(SWT.CENTER);
        tc.setWidth(200);

        // telephone column
        tc = new TableColumn(toInviteTable, SWT.NONE);
        tc.setText(contactColumnHeaders[3]);
        tc.setAlignment(SWT.CENTER);
        tc.setWidth(200);
    }

    /**
     * 给搜索结果表格添加一个双击响应事件
     */
    private void addInviteTableListener()
    {
        ToInviteBtnClickListener inviteBtnClickedListener = new ToInviteBtnClickListener();
        toInviteTable.addListener(SWT.MouseDoubleClick,
                inviteBtnClickedListener);
    }

    private void addDelButtonListener()
    {
        DelSelectedPersonAdapter delSelectedPersonAdapter = new DelSelectedPersonAdapter();
        delButton.addSelectionListener(delSelectedPersonAdapter);
    }

    public void freshInviteTable()
    {
        int inviteListSize = toInviteContactMap.size();
        if (inviteListSize > 0)
        {
            toInviteContactArray = new Person[inviteListSize];
            Collection<Person> valueCollection = toInviteContactMap.values();
            int i = 0;
            for (Person person : valueCollection)
            {
                toInviteContactArray[i] = person;
                i++;
            }
        }
        else
        {
            toInviteContactArray = null;
        }
        toInviteTableViewer.setInput(toInviteContactArray);

        if (null != toInviteTable)
        {
            for (int i = 0; i < 2; i++)
            {
                toInviteTable.getColumn(i).pack();
            }
        }
    }

    /**
     * Return the initial size of the dialog.
     */
    @Override
    protected Point getInitialSize()
    {
        return new Point(555, 306);
    }

    @Override
    protected void okPressed()
    {
        logger.debug("ok button pressed, try to save selected person");
        PersonInviteUtil.getInstance().setSelectedPerson(toInviteContactArray);
        super.okPressed();
    }

    /**
     * 代理方法实现
     * @see com.huawei.esdk.uc.sametime.widgets.PersonSelectHandlerInterface#handlePersonSelect(com.ibm.collaboration.realtime.people.Person)
     */
    @Override
    public void handlePersonSelect(Person personSelected)
    {
        if (null != personSelected)
        {
            String ucAccount = PluginUtil
                    .getUCAccountFromContactID(personSelected.getContactId());
            toInviteContactMap.put(ucAccount, personSelected);
        }

        freshInviteTable();
    }

    private static class InviteTableLabelProvider implements
            ITableLabelProvider
    {
        @Override
        public Image getColumnImage(Object arg0, int arg1)
        {
            return null;
        }

        @Override
        public String getColumnText(Object dataObj, int columnIndex)
        {
            Person person = (Person) dataObj;
            String result = null;
            switch (columnIndex)
            {
                case 0:
                    result = person.getDisplayName();
                    break;
                case 1:
                    result = PluginUtil.getUCAccountFromContactID(person
                            .getContactId());
                    break;
                case 2:
                {
                    Object telephone = PluginUtil.getPersonProperty(person,
                            DirectoryInfo.TELEPHONE);
                    if (null != telephone)
                    {
                        result = (String) telephone;
                    }
                    else
                    {
                        result = null;
                    }
                }
                    break;
                case 3:
                {
                    Object email = PluginUtil.getPersonProperty(person,
                            DirectoryInfo.TELEPHONE);
                    if (null != email)
                    {
                        result = (String) email;
                    }
                    {
                        result = null;
                    }

                }
                    break;
                default:
                    result = person.getContactId();
                    break;
            }
            return result;
        }

        @Override
        public void addListener(ILabelProviderListener arg0)
        {

        }

        @Override
        public void dispose()
        {

        }

        @Override
        public boolean isLabelProperty(Object arg0, String arg1)
        {
            return false;
        }

        @Override
        public void removeListener(ILabelProviderListener arg0)
        {

        }
    }

    private static class InviteTableContentProvider implements
            IStructuredContentProvider
    {
        @Override
        public Object[] getElements(Object arg0)
        {
            return (Person[]) arg0;
        }

        @Override
        public void dispose()
        {

        }

        @Override
        public void inputChanged(Viewer arg0, Object arg1, Object arg2)
        {

        }
    }

    private class DelSelectedPersonAdapter extends SelectionAdapter
    {
        @Override
        public void widgetSelected(SelectionEvent arg0)
        {
            int index = toInviteTable.getSelectionIndex();
            logger.debug("index " + index + "selectd"); //$NON-NLS-1$ //$NON-NLS-2$
            String keyToRemove = null;
            Person tempPerson = null;
            // 如果没有选中表格中的项,则index的值是-1.所以肯定要做大于等于0的判断
            if (index >= 0)
            {
                tempPerson = toInviteContactArray[index];
            }
            if (null != tempPerson)
            {
                keyToRemove = PluginUtil.getUCAccountFromContactID(tempPerson
                        .getContactId());
            }
            if (null != keyToRemove)
            {
                toInviteContactMap.remove(keyToRemove);
            }
            freshInviteTable();
        }
    }

    private class ToInviteBtnClickListener implements Listener
    {
        @Override
        public void handleEvent(Event arg0)
        {
            int index = toInviteTable.getSelectionIndex();
            logger.debug("index " + index + "selected"); //$NON-NLS-1$
            String keyToRemove = null;
            Person tempPerson = null;
            // 如果没有选中表格中的项,则index的值是-1.所以肯定要做大于等于0的判断
            if (index >= 0)
            {
                tempPerson = toInviteContactArray[index];
            }
            if (null != tempPerson)
            {
                keyToRemove = PluginUtil.getUCAccountFromContactID(tempPerson
                        .getContactId());
            }
            if (null != keyToRemove)
            {
                toInviteContactMap.remove(keyToRemove);
            }
            freshInviteTable();
        }
    }
}
